package com.kong.controller;

import com.github.abel533.database.Dialect;
import com.github.abel533.database.IntrospectedTable;
import com.github.abel533.database.SimpleDataSource;
import com.github.abel533.utils.DBMetadataUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.seed.mybatis.core.PageInfo;
import org.seed.mybatis.core.query.Query;
import org.seed.mybatis.core.query.param.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.burgeon.commons.react.Result;
import com.kong.dao.entity.GenerateHistory;
import com.kong.service.GenerateHistoryService;

import java.sql.SQLException;
import java.util.List;

/**
 * 代码生成记录
 *
 * @author glin
 * @date 2024-04-16
 */
@RestController
@RequestMapping("generate-history")
@Tag(name = "代码生成记录")
@Slf4j
public class GenerateHistoryController {

    @Autowired
    private GenerateHistoryService generateHistoryService;

    /**
     * 分页查询
     *
     * @param param 分页参数
     * @return
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询")
    @Parameters({
            @Parameter(name = "pageIndex", description = "当前页码"),
            @Parameter(name = "pageSize", description = "每页记录数")
    })
    public Result<PageInfo<GenerateHistory>> page(PageParam param) {
        Query query = param.toQuery();
        PageInfo<GenerateHistory> pageInfo = generateHistoryService.page(query);
        return Result.ok(pageInfo);
    }

    /**
     * 执行生成
     */
    @PostMapping("/generate")
    @Operation(summary = "执行生成")
    public Result<String> generate(String configId) {
        DBMetadataUtils dbUtils = new DBMetadataUtils(
                new SimpleDataSource(Dialect.MYSQL, "jdbc:mysql://10.100.11.76:3306/code-generate?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8", "root", "gAmboLpet31792"));

        try {
            List<IntrospectedTable> tables = dbUtils.introspectTables(dbUtils.getDefaultConfig());
            log.info("Tables: {}", tables.size());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return null;
    }


    /**
     * 删除记录
     *
     * @param id 主键id
     * @return
     */
    @DeleteMapping("/delete")
    @Operation(summary = "删除记录")
    public Result<Void> delete(String id) {
        generateHistoryService.deleteById(id);
        return Result.ok();
    }


    /**
     * 根据ID查询
     *
     * @param id 主键id
     * @return
     */
    @GetMapping("/get")
    @Operation(summary = "根据ID查询")
    public Result<GenerateHistory> get(String id) {
        GenerateHistory generateHistory = generateHistoryService.getById(id);
        return Result.ok(generateHistory);
    }

}